package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

/**
 * @param
 * @return
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LisenerLikeTimeMsg {
    private final IInteractionReplyService replyService;

    /**
     * 监听下单的消息
     *
     * @param likedTimesDTOS
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))

    public void lisenerMsg(List<LikedTimesDTO> likedTimesDTOS) {
        //健壮性判断
        if (ObjectUtil.isEmpty(likedTimesDTOS)) {
            log.error("监听的消息有误，点赞的数量为空。{}", likedTimesDTOS);
            return;
        }
        log.info("监测到点赞集合：{}", likedTimesDTOS);
        //1创建一个list集合
        List<InteractionReply> replyList = new ArrayList<>(likedTimesDTOS.size());
        //2.遍历likedTimesDTOS
        for (LikedTimesDTO likedTimesDTO : likedTimesDTOS) {
            //2.1创建LikedTimesDTO类封装数据
            InteractionReply reply = new InteractionReply();
            reply.setId(likedTimesDTO.getBizId());
            reply.setLikedTimes(likedTimesDTO.getLikedTimes());
            //2.2将对象LikedTimesDTO添加值list集合中
            replyList.add(reply);
        }
        //3.批量更新刀数据库中
        replyService.updateBatchById(replyList, 100);
    }
}
